package com.minjie.controller;

import com.minjie.pojo.Result;
import com.minjie.pojo.Task;
import com.minjie.pojo.User;
import com.minjie.service.TaskService;
import com.minjie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/tasks")
public class TaskController {

    @Autowired
    private UserService userService;
    @Autowired
    private TaskService taskService;
    //1.token ------> uid
    //2.设置task.uid = uid
    //3.将 task 作为参数传入 mapper 接口和 xml 文件中
    @PostMapping("/add")
    public Result addTask(@RequestHeader("Authorization") String token, @RequestBody Task task){
        try {
            User user = userService.getUserInfoByToken(token);
            taskService.addTask(task, user.getId());
            return Result.success();
        } catch (Exception e) {
            return Result.error("发生错误，无法添加事项");
        }
    }
    //1.根据 token 解析出来 uid，
    //2.将 uid 和事项信息存储数据库

    //1.getHead 得到 token
    //2.jwt 解析 token 得到 claims
    //3.claims 得到 uid
    @GetMapping("/mytasks")
    public Result getMyTasks(@RequestHeader("Authorization") String token){
        //⭐⭐
        try {
            User user = userService.getUserInfoByToken(token);
            List<Task> tasks = taskService.getTasksByUserId(user.getId());
            return Result.success(tasks);
        } catch (Exception e) {
            return Result.error("错误");

        }
    }


    @PutMapping("/update")
    public Result update(@RequestHeader("Authorization") String token, @RequestBody Task task){
        try {
            User user = userService.getUserInfoByToken(token);
            taskService.updateTask(task, user.getId());
            return Result.success();
        } catch (Exception e) {
            return Result.error("发生错误，无法添加事项");
        }
    }

}




